package student.tests;

import static org.junit.Assert.*;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;

import org.junit.BeforeClass;
import org.junit.Test;

import student.*;
import student.productions.*;

public class ParsePrintTest {

	private static Reader input;
	private static Writer output;
	private static Parser parser;
	
	@BeforeClass
	public static void setUpBeforeClass(){
		parser = new CritterParser();	
	}

	/**
	 * Checks that the parser works and that pretty print gives the expected output
	 */
	@Test
	public void simplePrettyPrint() {
		Node program = parser.parse(new StringReader("mem[3] < 4 --> eat;"));
		StringBuffer buf = new StringBuffer();
		program.prettyPrint(buf);
		String expected = "mem[3] < 4 \n-->\neat;";
		assertTrue("prettyPrint message did not match expected", buf.toString().equals(expected));
	}

	/**
	 * Tests that the parser works for larger programs
	 */
	@Test
	public void complexPrettyPrint(){
		try {
			input = new FileReader(new File("testInput.txt"));
			Node program = parser.parse(input);
			StringBuffer buf = new StringBuffer();
			program.prettyPrint(buf);
			output = new PrintWriter(new File("testOutput.txt"));
			output.write(buf.toString());
			output.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * Tests that the output of prettyPrint is still a valid program
	 * Failure would cause exceptions in the parser
	 */
	@Test
	public void reParse(){
		try {
			input = new FileReader(new File("testInput.txt"));
			Node program = parser.parse(input);
			StringBuffer buf = new StringBuffer();
			program.prettyPrint(buf);
			output = new PrintWriter(new File("firstOutput.txt"));
			output.write(buf.toString());
			output.close();
			input = new FileReader(new File("firstOutput.txt"));
			program = parser.parse(input);
			buf = new StringBuffer();
			program.prettyPrint(buf);
			output = new PrintWriter(new File("secondOutput.txt"));
			output.write(buf.toString());
			output.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}
